import {Request, Response, Router} from "express";
import {GamesModel} from "../models/gamesModel";
import {EcpmModel} from "../models/ecpmModel";
import logger from "../logger";
import {getJson} from "../utils";

require('express-async-errors');

export const ecpm_router: Router = Router();
ecpm_router.get('/all', async (req: Request, res: Response) => {
    res.json(await EcpmModel.find().limit(10));
});

ecpm_router.get('/update', async (req: Request, res: Response) => {
    res.json('update');
});

ecpm_router.get('/query', async (req: Request, res: Response) => {
    try {
        const startTime = parseInt(req.query.startTime as string);
        const endTime = parseInt(req.query.endTime as string);
        const appids = req.query.appids as string[]; // 假设多个游戏名称以逗号分隔
        const page = parseInt(req.query.page as string) || 1; // 默认页码为 1
        const pageSize = parseInt(req.query.pageSize as string) || 10; // 默认每页显示 10 条记录
        const costMin = parseInt(req.query.costMin as string) || 0;
        const open_id = req.query.open_id as string;
        const is_me = req.query.is_me as string;
        logger.info(is_me);
        res.json(await fetchEventsByTimeAndGameNames(startTime, endTime, appids, page, pageSize, costMin, open_id, is_me));
    } catch (err) {
        logger.error(err);
    }
});

async function fetchEventsByTimeAndGameNames(
    startTime: number,
    endTime: number,
    appids: string[],
    page: number,
    pageSize: number,
    costMin: number,
    open_id: string,
    is_me: string
) {
    try {
        const skip = (page - 1) * pageSize;


        const match: any = {
            event_time: {$gte: startTime, $lte: endTime},
            cost: {$gte: costMin},
        };

        const excludeAppids = await getJson();
        if (is_me === '1') {
            if (appids && appids.length > 0) {
                match.appid = {$in: excludeAppids.filter(item => appids.includes(item))};
            } else {
                match.appid = {$in: excludeAppids};
            }
        } else {
            match.appid = {$nin: excludeAppids};
            if (appids && appids.length > 0) {
                match.appid = {...match.appid, $in: appids};
            }
        }
        if (open_id !== '' && open_id) {
            match.open_id = open_id;
        }
        logger.info({match, appids});

        const pipeline = [
            {$match: match},
            {$sort: {event_time: -1 as 1 | -1}}, // 按 event_time 字段倒序排序
            {
                $lookup: {
                    from: 'users',
                    localField: 'open_id',
                    foreignField: 'openid',
                    as: 'user_info'
                }
            },
            {
                $facet: {
                    metadata: [{$count: "total"}],
                    data: [
                        {$skip: skip},
                        {$limit: pageSize},
                        {
                            $project: {
                                _id: 0,
                                appid: 1,
                                cost: 1,
                                event_time: 1,
                                event_name: 1,
                                open_id: 1,
                                ips: {$arrayElemAt: ['$user_info.ips', 0]}
                            }
                        },
                    ],
                    totalCost: [{$group: {_id: null, totalCost: {$sum: "$cost"}}}],
                },
            },
        ];

        const results: any[] = await EcpmModel.aggregate(pipeline);

        const total = results[0].metadata.length > 0 ? results[0].metadata[0].total : 0;
        const data = results[0].data;
        const totalCost = results[0].totalCost.length > 0 ? results[0].totalCost[0].totalCost : 0;

        return {total, data, totalCost};
    } catch (error) {
        console.error('Error fetching data:', error);
        return {total: 0, data: null, totalCost: 0}
    }
}